package service

import (
	"backend_api/internal/global"
	"backend_api/internal/model"
	"backend_api/internal/model/request"
	"errors"
	"gorm.io/gorm"
)

type ToolCategoryService struct {
}

// GetToolCategoryList 获取工具分类列表
func (s *ToolCategoryService) GetToolCategoryList(req *request.ToolCategoryListReq) (list []model.ToolCategory, total int64, err error) {

	query := global.DB.Model(&model.ToolCategory{})
	if req.Name != "" {
		query = query.Where("name LIKE ?", "%"+req.Name+"%")
	}

	_ = query.Count(&total).Error

	err = query.Order("sort DESC").
		Offset((req.Page - 1) * req.PageSize).
		Limit(req.PageSize).
		Find(&list).Error

	return
}

// AddToolCategory 添加工具分类
func (s *ToolCategoryService) AddToolCategory(req *request.ToolCategoryAddReq) error {
	// 检查分类名称是否已存在
	var count int64
	if err := global.DB.Model(&model.ToolCategory{}).Where("name = ?", req.Name).Count(&count).Error; err != nil {
		return err
	}
	if count > 0 {
		return errors.New("分类名称已存在")
	}

	// 创建新的分类记录
	category := &model.ToolCategory{
		Name: req.Name,
		Path: req.Path,
		Sort: req.Sort,
	}
	// 保存到数据库
	if err := global.DB.Create(category).Error; err != nil {
		return err
	}

	return nil
}

// UpdateToolCategory 更新工具分类
func (s *ToolCategoryService) UpdateToolCategory(req *request.ToolCategoryUpdateReq) error {
	// 检查分类是否存在
	var category model.ToolCategory
	err := global.DB.First(&category, req.ID).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return errors.New("分类更新失败")

		}
		return err
	}

	// 更新分类信息
	return global.DB.Model(&category).Updates(map[string]interface{}{
		"name": req.Name,
		"sort": req.Sort,
		"path": req.Path,
	}).Error
}

// DeleteToolCategory 删除工具分类
func (s *ToolCategoryService) DeleteToolCategory(req *request.ToolCategoryDeleteReq) error {
	// 检查分类是否存在
	var category model.ToolCategory
	err := global.DB.First(&category, req.ID).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return errors.New("删除分类失败")
		}
		return err
	}

	//// 检查分类下是否有工具
	var count int64
	err = global.DB.Model(&model.Tool{}).Where("category_id = ?", req.ID).Count(&count).Error
	if err != nil {
		return err
	}
	if count > 0 {
		return errors.New("当前分类存在工具不可删除")
	}

	// 删除分类
	return global.DB.Delete(&category).Error
}
